package com.feimaopian.config;

import com.feimaopian.entity.User;
import com.feimaopian.service.UserServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImpl userMapper;

    //授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        System.out.println("执行授权逻辑");
        return null;
    }

    //认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证逻辑");

        //编写shiro判断逻辑，判断用户名和密码
        //1. 判断用户名
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        User user = userMapper.findById(userToken.getUsername());
        if (user == null) {
            //用户名不存在shiro底层会抛出UnknownAccountException
            return null;
        }
        //2. 判断密码,参数1：需要返回给login方法的数据；参数2：数据库密码，shiro会自动判断
        return new SimpleAuthenticationInfo("",user.getPwd(), "");
    }

}
